<template>
  <div class="health-info-detail-page">
    <van-nav-bar
      title="资讯详情"
      left-arrow
      @click-left="router.back()"
    >
      <template #right>
        <div class="share-icon">
          <van-icon name="share-o" size="20" />
        </div>
      </template>
    </van-nav-bar>
    
    <div v-if="loading" class="loading-container">
      <van-loading type="spinner" size="24px" vertical>加载中...</van-loading>
    </div>
    
    <template v-else-if="article">
      <div class="article-header">
        <div class="header-content">
          <h1 class="article-title">{{ article.title }}</h1>
          <div class="article-subtitle">{{ article.content }}</div>
          <div class="article-meta-info">
            <div class="read-count">
              <van-icon name="eye-o" class="meta-icon" />
              <span>{{ article.viewCnt }}人已读</span>
            </div>
            <div class="publish-info" v-if="article.createdAt">
              <van-icon name="clock-o" class="meta-icon" />
              <span>{{ formatDate(article.createdAt) }}</span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 医生信息 -->
      <div class="doctor-card" v-if="doctor">
        <div class="doctor-header">
          <div class="doctor-info">
            <div class="doctor-avatar">
              <img v-if="doctor?.avatar" :src="doctor.avatar" alt="医生头像" />
              <div v-else class="avatar-placeholder">
                <van-icon name="manager" size="28" />
              </div>
            </div>
            <div class="doctor-detail">
              <div class="doctor-name">
                {{ doctor?.doctorName || '张三' }}
                <span class="doctor-badge">{{ doctor?.doctorTitle || '主任医师' }}</span>
              </div>
              <div class="doctor-dept">
                <van-icon name="location-o" class="dept-icon" />
                {{ doctor?.department || '内科' }} {{ doctor?.hospital || '未知医院' }}
              </div>
            </div>
          </div>
          <div class="follow-btn" :class="{ 'followed': isFollowing }" @click="toggleFollow">
            <van-icon :name="isFollowing ? 'success' : 'plus'" size="14" />
            <span>{{ isFollowing ? '已关注' : '关注' }}</span>
          </div>
        </div>
      </div>
      
      <!-- 医生回答内容 -->
      <div class="answer-content" v-if="doctor" v-html="formattedAnswer"></div>
      

      
      <!-- 底部工具栏 -->
      <div class="bottom-toolbar">
        <div class="comment-input" @click="showCommentInput = true">
          <van-icon name="chat-o" class="comment-icon" />
          <span>暂无法评论</span>
        </div>
        <div class="actions">
          <div class="action-btn collect-btn" :class="{ 'active': isCollected }" @click="toggleCollect">
            <van-icon :name="isCollected ? 'star' : 'star-o'" class="action-icon" />
            <span>收藏</span>
          </div>
          <div class="action-btn like-btn" :class="{ 'active': isLiked }" @click="toggleLike">
            <van-icon :name="isLiked ? 'like' : 'like-o'" class="action-icon" />
            <span>{{ article.likeCnt || 0 }}</span>
          </div>
        </div>
      </div>
    </template>
    
    <van-popup v-model:show="showCommentInput" position="bottom" round>
      <div class="comment-popup">
        <div class="comment-header">
          <span>评论</span>
          <van-icon name="cross" @click="showCommentInput = false" />
        </div>
        <div class="comment-form">
          <van-field
            v-model="commentText"
            placeholder="写下您的评论..."
            rows="3"
            type="textarea"
            maxlength="200"
            show-word-limit
          />
          <van-button type="primary" block @click="submitComment">发布评论</van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { showToast } from 'vant';
import { axiosrnewmedical } from '@/http/axiosRead';
import { axioswnewmedical } from '@/http/axiosWrtie';

// 定义文章接口
interface ArticleDetail {
  id: number;
  catId: number;
  categoryName: string;
  title: string;
  content: string;
  authorId?: number;
  authorName?: string;
  likeCnt: number;
  viewCnt: number;
  status?: string;
  createdAt?: string;
  tags?: string;
}

interface DoctorAnswer {
  id: number;
  questionId: number;
  content: string;
  doctorId: number;
  doctorName: string;
  doctorTitle: string;
  department: string;
  hospital: string;
  avatar: string;
  likeCnt: number;
  createdAt: string;
}

interface ArticleResponse {
  question: ArticleDetail;
  answers: DoctorAnswer[];
}

// 定义互动请求参数接口
interface InteractParams {
  userId: number;  // 用户ID
  objType: string; // 对象类型：question/answer
  objId: number;   // 对象ID
  action: string;  // 操作类型：like/fav/follow
}

const route = useRoute();
const router = useRouter();
const loading = ref(true);
const article = ref<ArticleDetail | null>(null);
const doctor = ref<DoctorAnswer | null>(null);
const isLiked = ref(false);
const isCollected = ref(false);
const isFollowing = ref(false);
const showCommentInput = ref(false);
const commentText = ref('');
const userId = ref(1); // 临时写死用户ID，实际项目中应该从用户登录状态获取

// 确保有临时token用于测试
const ensureToken = () => {
  const token = localStorage.getItem("token");
  if (!token) {
    // 设置一个临时测试token
    localStorage.setItem("token", "test-token-for-interact-api");
    console.log('已设置临时token用于API测试');
  }
};

// 格式化医生回答内容
const formattedAnswer = computed(() => {
  if (!doctor.value || !doctor.value.content) return '';
  
  // 将\r\n替换为<br/>，便于显示换行
  let content = doctor.value.content.replace(/\r\n|\n/g, '<br/>');
  
  // 将标题样式加粗
  content = content.replace(/^(\d+[、.．])\s*(.+)$/gm, '<h3>$1 $2</h3>');
  
  return content;
});

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return '';
  try {
    const date = new Date(dateStr);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
  } catch {
    return dateStr;
  }
};

// 设置模拟数据
const setMockData = (id: string | string[]) => {
  article.value = {
    id: Number(id),
    catId: 1,
    categoryName: '中医常识',
    title: '菱角的功效与作用',
    content: '菱角的功效与作用',
    authorId: 1,
    authorName: '张医生',
    likeCnt: 520,
    viewCnt: 2000,
    status: 'published',
    createdAt: '2020-01-01 15:20:20',
    tags: '中医常识'
  };
  
  // 设置模拟医生信息
  doctor.value = {
    id: 1,
    questionId: Number(id),
    doctorId: 1,
    doctorName: '刘医生',
    doctorTitle: '主任医师',
    department: '门诊外一科',
    hospital: '四川省保健院克苑',
    avatar: '',
    likeCnt: 520,
    createdAt: '2020-01-01 15:20:20',
    content: `菱角是一年生草本水生植物菱的果实，菱角皮脆肉美，蒸煮后剥壳食用，亦可熬粥。菱角含有丰富的蛋白质、不饱和脂肪酸及多种维生素和微量元素，具有利尿通乳，止渴，解酒毒的功效。

1、补脾益气

菱角生食有清暑解热作用，熟食则有益气健脾功效。

2、抗癌

菱角还能起到"醒酒"、解酒、缓中"的用途。民间单方中还有它治疗胃癌、食道癌的作用。近代中药资料表明，菱实的醇浸水液有抗癌作用。

3、减肥

菱角利尿，通乳，止消渴，解酒毒，主治疮毒，赘疣，且是减肥的辅助食品。

4、缓解皮肤病

菱角食用，外用均可，以辅助治疗小儿头疮，头面黄水疮，皮肤赘疣等多种皮肤病。`
  };
};

// 获取文章详情
const fetchArticleDetail = async () => {
  loading.value = true;
  const id = route.params.id;
  
  try {
    const res = await axiosrnewmedical.get(`/Consult/detail/${id}`);
    if (res.data && res.data.code === 200) {
      const data = res.data.data as ArticleResponse;
      article.value = data.question;
      
      // 设置医生信息（来自第一个回答）
      if (data.answers && data.answers.length > 0) {
        doctor.value = data.answers[0];
      }
      
      // 获取用户互动状态
      fetchUserInteractions();
    } else {
      // 使用模拟数据
      setMockData(id);
      fetchUserInteractions();
    }
  } catch (error) {
    console.error('获取文章详情失败:', error);
    // 使用模拟数据
    setMockData(id);
    fetchUserInteractions();
  } finally {
    loading.value = false;
  }
};

// 获取用户互动状态（点赞、收藏、关注）
const fetchUserInteractions = async () => {
  if (!article.value) return;

  try {
    // 调用查询用户互动状态的API - 使用正确的接口路径
    const url = `/Consult/GetUserInteractStatus?userId=${userId.value}&objType=question&objId=${article.value.id}`;
    const res = await axiosrnewmedical.get(url);
    
    if (res.data && res.data.code === 200) {
      // 更新互动状态
      isLiked.value = res.data.data.isLiked || false;
      isCollected.value = res.data.data.isFavorited || false;
      
      // 如果有医生信息，获取关注状态
      if (doctor.value) {
        const doctorUrl = `/Consult/GetUserInteractStatus?userId=${userId.value}&objType=answer&objId=${doctor.value.id}`;
        const doctorRes = await axiosrnewmedical.get(doctorUrl);
        if (doctorRes.data && doctorRes.data.code === 200) {
          isFollowing.value = doctorRes.data.data.isFollowed || false;
        }
      }
    } else {
      // 请求失败，使用默认值
      isLiked.value = false;
      isCollected.value = false;
      isFollowing.value = false;
    }
    
  } catch (error) {
    console.error('获取用户互动状态失败:', error);
    
    // 如果是404错误，使用本地存储作为fallback
    if ((error as { response?: { status?: number } })?.response?.status === 404) {
      console.log('互动接口不存在，使用本地存储状态');
      const localData = localStorage.getItem(`interactions_${article.value.id}`);
      if (localData) {
        try {
          const data = JSON.parse(localData);
          isLiked.value = data.isLiked || false;
          isCollected.value = data.isCollected || false;
          isFollowing.value = data.isFollowing || false;
        } catch (parseError) {
          console.error('解析本地存储数据失败:', parseError);
          // 使用默认值
          isLiked.value = false;
          isCollected.value = false;
          isFollowing.value = false;
        }
      } else {
        // 使用默认值
        isLiked.value = false;
        isCollected.value = false;
        isFollowing.value = false;
      }
    } else {
      // 其他错误，使用默认值
    isLiked.value = false;
    isCollected.value = false;
    isFollowing.value = false;
    }
  }
};

// 发送互动请求
const sendInteractRequest = async (params: InteractParams) => {
  try {
    // 检查token是否存在
    const token = localStorage.getItem("token");
    console.log('当前token状态:', token ? '已存在' : '不存在');
    
    // 调用后端互动API - 使用正确的接口路径
    const url = `/Consult/interact?userId=${params.userId}&objType=${params.objType}&objId=${params.objId}&action=${params.action}`;
    console.log('发送互动请求:', url);
    
    const res = await axioswnewmedical.post(url, {});
    
    if (res.data && res.data.code === 200) {
      showToast('操作成功');
      return true;
    } else {
      console.log('API响应错误:', res.data);
      showToast(res.data?.msg || '操作失败，请稍后重试');
      return false;
    }
  } catch (error) {
    console.error('发送互动请求失败:', error);
    console.error('错误详情:', (error as { response?: { data?: unknown } })?.response?.data);
    
    // 如果是404错误，使用本地存储作为fallback
    if ((error as { response?: { status?: number } })?.response?.status === 404) {
      console.log('互动写入接口不存在，使用本地存储模拟');
      
      try {
        // 保存到本地存储
        const currentData = localStorage.getItem(`interactions_${params.objId}`) || '{}';
        const data = JSON.parse(currentData);
        
        if (params.action === 'like') {
          data.isLiked = !data.isLiked;
        } else if (params.action === 'fav') {
          data.isCollected = !data.isCollected;
        } else if (params.action === 'follow') {
          data.isFollowing = !data.isFollowing;
        }
        
        localStorage.setItem(`interactions_${params.objId}`, JSON.stringify(data));
        console.log('本地存储互动状态已更新:', data);
        showToast('操作成功');
        return true;
        
      } catch (storageError) {
        console.error('本地存储操作失败:', storageError);
        showToast('操作失败，请稍后重试');
        return false;
      }
    } else {
    showToast('操作失败，请稍后重试');
    return false;
    }
  }
};

// 切换点赞状态
const toggleLike = async () => {
  if (!article.value) return;
  
  const newStatus = !isLiked.value;
  const params: InteractParams = {
    userId: userId.value,
    objType: 'question',
    objId: article.value.id,
    action: 'like'
  };
  
  const success = await sendInteractRequest(params);
  
  if (success) {
    isLiked.value = newStatus;
    if (article.value) {
      if (newStatus) {
        article.value.likeCnt = (article.value.likeCnt || 0) + 1;
      } else {
        article.value.likeCnt = Math.max((article.value.likeCnt || 0) - 1, 0);
      }
    }
  }
};

// 切换收藏状态
const toggleCollect = async () => {
  if (!article.value) return;
  
  const newStatus = !isCollected.value;
  const params: InteractParams = {
    userId: userId.value,
    objType: 'question',
    objId: article.value.id,
    action: 'fav'
  };
  
  const success = await sendInteractRequest(params);
  
  if (success) {
    isCollected.value = newStatus;
    showToast(newStatus ? '收藏成功' : '已取消收藏');
  }
};

// 切换关注状态
const toggleFollow = async () => {
  if (!doctor.value) return;
  
  const newStatus = !isFollowing.value;
  const params: InteractParams = {
    userId: userId.value,
    objType: 'answer',
    objId: doctor.value.id,
    action: 'follow'
  };
  
  const success = await sendInteractRequest(params);
  
  if (success) {
    isFollowing.value = newStatus;
    showToast(newStatus ? '关注成功' : '已取消关注');
  }
};

// 提交评论
const submitComment = () => {
  if (!commentText.value.trim()) {
    showToast('评论内容不能为空');
    return;
  }
  
  // 这里可以调用提交评论接口
  // axioswnewmedical.post('/Consult/comment', { id: article.value.id, content: commentText.value });
  
  showToast('评论成功');
  showCommentInput.value = false;
  commentText.value = '';
};

onMounted(() => {
  ensureToken(); // 确保有token用于API调用
  fetchArticleDetail();
});
</script>

<style scoped>
.health-info-detail-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  padding-bottom: 80px;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.article-header {
  background: linear-gradient(135deg, #ffffff 0%, #fafbfc 100%);
  margin: 16px;
  border-radius: 20px;
  padding: 24px 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(255, 255, 255, 0.8);
}

.header-content {
  width: 100%;
}

.article-title {
  font-size: 22px;
  font-weight: 700;
  color: #1a202c;
  margin: 0 0 16px 0;
  line-height: 1.4;
  letter-spacing: -0.02em;
}

.article-subtitle {
  font-size: 16px;
  line-height: 1.6;
  color: #4a5568;
  margin-bottom: 20px;
  padding: 16px;
  background: linear-gradient(135deg, #f7fafc 0%, #edf2f7 100%);
  border-radius: 12px;
  border-left: 4px solid #4299e1;
}

.article-meta-info {
  display: flex;
  gap: 20px;
  align-items: center;
}

.read-count, .publish-info {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  color: #718096;
}

.meta-icon {
  color: #a0aec0;
  font-size: 14px;
}

.doctor-card {
  background: linear-gradient(135deg, #ffffff 0%, #fafbfc 100%);
  margin: 16px;
  border-radius: 16px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
  border: 1px solid rgba(255, 255, 255, 0.8);
}

.doctor-header {
  padding: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.doctor-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.doctor-avatar {
  width: 52px;
  height: 52px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.doctor-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  color: #ffffff;
  width: 100%;
  height: 100%;
}

.doctor-detail {
  flex: 1;
}

.doctor-name {
  font-size: 17px;
  font-weight: 600;
  color: #2d3748;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.doctor-badge {
  background: linear-gradient(135deg, #4299e1 0%, #3182ce 100%);
  color: white;
  padding: 2px 8px;
  border-radius: 8px;
  font-size: 11px;
  font-weight: 500;
}

.doctor-dept {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  color: #718096;
}

.dept-icon {
  color: #a0aec0;
  font-size: 12px;
}

.follow-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  background: linear-gradient(135deg, #4299e1 0%, #3182ce 100%);
  color: white;
  border-radius: 20px;
  font-size: 13px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(66, 153, 225, 0.3);
}

.follow-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(66, 153, 225, 0.4);
}

.follow-btn.followed {
  background: linear-gradient(135deg, #48bb78 0%, #38a169 100%);
  box-shadow: 0 2px 8px rgba(72, 187, 120, 0.3);
}

.answer-content {
  background: linear-gradient(135deg, #ffffff 0%, #fafbfc 100%);
  margin: 16px;
  border-radius: 16px;
  padding: 24px 20px;
  font-size: 15px;
  line-height: 1.7;
  color: #4a5568;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
  border: 1px solid rgba(255, 255, 255, 0.8);
}

.answer-content :deep(h3) {
  font-size: 18px;
  font-weight: 600;
  margin: 20px 0 12px;
  color: #2d3748;
  position: relative;
  padding-left: 20px;
}

.answer-content :deep(h3):before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  width: 4px;
  height: 18px;
  background: linear-gradient(135deg, #4299e1 0%, #3182ce 100%);
  border-radius: 2px;
  transform: translateY(-50%);
}



.bottom-toolbar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background: linear-gradient(135deg, #ffffff 0%, #fafbfc 100%);
  border-top: 1px solid rgba(241, 245, 249, 0.8);
  box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.08);
  backdrop-filter: blur(10px);
}

.actions {
  display: flex;
  gap: 20px;
}

.action-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  padding: 8px 12px;
  border-radius: 12px;
  font-size: 12px;
  color: #718096;
  transition: all 0.3s ease;
  cursor: pointer;
}

.action-btn:hover {
  background-color: rgba(66, 153, 225, 0.1);
  transform: translateY(-1px);
}

.action-icon {
  font-size: 20px;
  transition: all 0.3s ease;
}

.collect-btn.active {
  color: #f6ad55;
}

.collect-btn.active .action-icon {
  color: #f6ad55;
}

.like-btn.active {
  color: #4299e1;
}

.like-btn.active .action-icon {
  color: #4299e1;
}

.comment-input {
  flex: 1;
  margin-right: 20px;
  background: linear-gradient(135deg, #f7fafc 0%, #edf2f7 100%);
  padding: 12px 16px;
  border-radius: 20px;
  color: #718096;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid rgba(226, 232, 240, 0.8);
}

.comment-input:hover {
  background: linear-gradient(135deg, #edf2f7 0%, #e2e8f0 100%);
  transform: translateY(-1px);
}

.comment-icon {
  color: #a0aec0;
  font-size: 16px;
}

.comment-popup {
  padding: 16px;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.comment-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.share-icon {
  padding: 0 8px;
}
</style> 